"""
Case Type   : 修改SSH端口后添加服务器，添加成功
Case Name   : 修改SSH端口后进行添加服务器，添加成功
Create At   : 2025/05/10
Owner       : @l1azzzy
Description :
    1.修改SSH端口
    2.导入服务器
    3.进行连通性检测
    4.恢复环境
Expect      :
    1.成功
    2.成功
    3.成功
    4.成功
History     :
"""

import os
import unittest
from yat.test import Node
from yat.test import macro
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Logger import Logger
from testcase.utils.datakit_api.CommonApi import CommonApi
from testcase.utils.datakit_api.BaseOpsApi import BaseOpsApi


class Tools(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f"-----{os.path.basename(__file__)} start-----")
        self.com_sh = CommonSH()
        self.token = self.com_sh.get_token_value(macro.DATAKIT_PASSWD)
        self.log.info(self.token)
        self.assertNotEqual("error", self.token)
        self.com_api = CommonApi(self.token)
        self.base_ops_api = BaseOpsApi(self.token)
        self.pri_node = Node('PrimaryDbUser')
        self.pri_node_root = Node('PrimaryRoot')
        self.server_name = 'test_001'
        self.data1 = {"isRemember": True,
                      "password": f"{self.pri_node_root.ssh_password}",
                      "port": 2222,
                      "privateIp": f"{self.pri_node_root.ssh_host}",
                      "publicIp": f"{self.pri_node_root.ssh_host}",
                      "remark": "",
                      "username": f"{self.pri_node_root.ssh_user}"}
        self.log.info(self.data1)
        text = '-----修改SSH端口 expect:成功-----'
        self.log.info(text)
        self.log.info('----备份SSH配置文件----')
        res = self.pri_node_root.sh(f'cp /etc/sshd_config /etc/sshd_config.bak')
        self.log.info('----修改SSH端口----')
        res = self.pri_node_root.sh(f"sed -i '/^#*Port /s/^#*Port .*/Port 2222/' /etc/ssh/sshd_config")
        self.log.info(res)
        self.log.info('----重启SSH服务----')
        res = self.pri_node_root.sh(f"systemctl restart sshd")
        self.log.info(res)
        self.log.info('----查看SSH端口是否修改成功----')
        res = self.pri_node_root.sh(f"ss -tnlp | grep 2222")
        self.log.info(res)
        self.assertIn('2222', res, 'SSH端口修改失败')

    def test_batch_installation(self):
        text = '----step1:导入服务器 expect:成功----'
        self.log.info(text)
        self.log.info('----联通性测试----')
        res1 = self.com_api.post_host_ping(self.data1)
        self.log.info(res1.json())
        self.assertEqual(200, res1.json()['code'], "连接信息不可用")
        self.log.info('----导入服务器----')
        res2 = self.com_api.post_host(self.data2)
        self.log.info(res2.json())
        self.assertEqual(200, res2.json()['code'], "导入服务器失败")
        self.log.info('----查看服务器导入是否成功----')
        res3 = self.com_api.get_host_page(name=f"{self.pri_node_root.ssh_host}")
        self.log.info(res3.json())
        self.assertEqual(1, res3.json()['total'], '服务器添加失败')

    def tearDown(self):
        text = '----恢复环境 expect:成功----'
        self.log.info(text)
        self.log.info('----恢复SSH配置文件----')
        res = self.pri_node_root.sh(f'rm -f /etc/sshd_config && cp /etc/sshd_config.bak /etc/sshd_config')
        self.log.info('----重启SSH服务----')
        res = self.pri_node_root.sh(f"systemctl restart sshd")
        self.log.info(res)
        self.log.info('----查看SSH端口是否修改成功----')
        res = self.pri_node_root.sh(f"ss -tnlp | grep 22")
        self.log.info(res)
        self.assertIn('22', res, 'SSH端口修改失败')
        text = '----查询服务器是否存在 expect：成功----'
        self.log.info(text)
        res6 = self.com_api.get_host_page(name=f"{self.pri_node_root.ssh_host}")
        self.log.info(res6.json())
        self.assertFalse(res6.json()['total'] > 1, '服务器管理功能异常')
        if res6.json()['total'] == 1:
            self.log.info('----清理环境,删除服务器----')
            res7 = self.com_api.delete_host(res6.json()['rows'][0]['hostId'])
            self.log.info(res7.json())
            self.assertEqual(200, res7.json()['code'], '删除服务器失败')
            res8 = self.com_api.get_host_page(name=f'{self.pri_node_root.ssh_host}')
            self.log.info(res8.json())
            self.assertEqual(0, res8.json()['total'], '删除服务器异常')
        else:
            self.log.info('----无需清理环境----')
        self.log.info(f"-----{os.path.basename(__file__)} finsh-----")
